<template>
  <div>
    <!--  面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
    <!--添加角色按钮-->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!--表格数据区域-->
      <el-table
        :data="rolesList"
        border
        style="width: 100%">
<!--        展开列-->
        <el-table-column type="expand">
          <template slot-scope="scope">
<!--            <pre>{{scope.row}}</pre>-->
            <el-row v-for="(item1,i1) in scope.row.children" :key="item1.id" :class="['bdbottom',i1===0?'bdtop':'', 'vcenter']">
              <!--渲染一级权限-->
              <el-col :span="5">
                <el-tag closable @close="removeRightsById(scope.row,item1.id)">
                  {{item1.authName}}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--渲染二级三级权限-->
              <el-col :span="19">
                <el-row v-for="(item2,i2) in item1.children" :key="item2.id" :class="[i2===0?'':'bdtop', 'vcenter']">
<!--                  通过for循环嵌套渲染二级权限-->
<!--                  二级权限-->
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightsById(scope.row,item2.id)">
                      {{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
<!--                  三级权限-->
                  <el-col :span="18">
                    <el-tag v-for="item3 in item2.children" :key="item3.id" type="warning" closable @close="removeRightsById(scope.row,item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
<!--        索引列-->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称">
        </el-table-column>
        <el-table-column
          prop="roleDesc"
          label="角色描述">
        </el-table-column>
        <el-table-column
          prop="address"
          label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRoleRights(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
<!--      分配 角色权限 的对话框-->
      <el-dialog
        title="分配权限"
        :visible.sync="setRoleRightsDialogVisible"
        width="40%" @close="setRoleRightsDialogClosed">
<!--        树形控件-->
        <el-tree :data="rightsList" :props="treeProps" show-checkbox default-expand-all node-key="id" :default-checked-keys="defKeys" ref="treeRef">
        </el-tree>
        <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleRightsDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible = false" v-on:click="allotRights">确 定</el-button>
  </span>
      </el-dialog>

    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data () {
    return {
      rolesList: [],
      rightsList: [],
      setRoleRightsDialogVisible: false,
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点id值的数组
      defKeys: [],
      // 即将 要分配的 角色的id
      roleId: ''
    }
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败!')
      this.rolesList = res.data
      // console.log(this.rolesList)
    },
    removeRightsById (roleInfo, rightId) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // console.log(v1, v2)
        // 删除用户权限
        const { data: res } = await this.$http.delete(`roles/${roleInfo.id}/rights/${rightId}`)
        if (res.meta.status !== 200) return this.$message.error('删除权限失败!')
        this.$message.success('删除权限成功!')
        // 更新角色列表数据
        // await this.getRolesList()
        roleInfo.children = res.data
      }).catch(err => {
        this.$message.info('取消了删除操作!')
        return err
      })
      // console.log(id)
    },
    async setRoleRights (role) {
      // 保存要分配的角色的id
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      // console.log(res.data)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色权限失败！')
      }
      // 将分配的角色权限保存到data中
      this.rightsList = res.data
      // console.log(this.rightsList)
      // console.log(role)
      // 递归获取三级节点id
      this.getLeafKeys(role, this.defKeys)
      // 显示 分配角色权限 的对话框
      this.setRoleRightsDialogVisible = true
    },
    // 监听 分配角色权限的对话框 的关闭
    setRoleRightsDialogClosed () {
      // 清空 默认选中的节点id值的数组
      this.defKeys = []
    },
    // 递归找到角色三级权限下的id 保存到 defKeys 数组中
    getLeafKeys (node, arr) {
      if (!node.children) {
        // 如果当前node节点不包含 children 属性，
        // 则为三级节点，将节点id保存到数组中
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 分配角色的权限
    async allotRights () {
      // 获取全选中的节点id
      const checkId = this.$refs.treeRef.getCheckedKeys()
      // 获取半选中的节点id
      const halfcheckId = this.$refs.treeRef.getHalfCheckedKeys()
      // console.log(checkId)
      const keys = [...checkId, ...halfcheckId]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败！')
      }
      this.$message.success('分配角色权限成功！')
      // 关闭对话框
      this.setRoleRightsDialogVisible = false
      // 重新加载数据
      this.getRolesList()
      // console.log(res)
    }
  },
  created () {
    this.getRolesList()
  }
}
</script>

<style scoped>
  .el-tag {
    margin: 7px;
  }
  .bdbottom {
    border-bottom: 1px solid #eee;
  }
  .bdtop {
    border-top: 1px solid #eee;
  }
  .vcenter {
    display: flex;
    align-items: center;
  }
</style>
